package com.example.service.impl;

import com.example.mapper.ReportMapper;
import com.example.mapper.MessagesMapper;
import com.example.mapper.ConversationsMapper;
import com.example.pojo.Conversations;
import com.example.pojo.Messages;
import com.example.pojo.PageBean;
import com.example.pojo.Report;
import com.example.service.ReportService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private ConversationsMapper conversationsMapper;
    @Autowired
    private MessagesMapper messagesMapper;

    // 获取Report列表
    @Override
    public PageBean<Report> list(Integer pageNum, Integer pageSize, String status) {
        // 1. 开启分页
        PageHelper.startPage(pageNum, pageSize);

        // 2. 执行查询
        List<Report> reports = reportMapper.list(status);
        Page<Report> page = (Page<Report>) reports;

        // 3. 封装分页结果
        return new PageBean<>(page.getTotal(), page.getResult());
    }

    // 根据id查看某条Report
    @Override
    public Report findById(Integer id) {
        return reportMapper.findById(id);
    }

    // 处理举报
    @Override
    @Transactional
    public void resolveReport(Integer reportId, Integer stuId) {
        try {
            log.info("开始处理举报: reportId={}, stuId={}", reportId, stuId);

            // 1. 更新举报状态为已处理
            reportMapper.updateToResolved(reportId);
            log.info("更新举报状态成功");

            // 2. 查找是否存在管理员与该学生的对话
            Conversations existingConversation = conversationsMapper.findAdminConversation(stuId);
            log.info("查询现有对话结果: {}", existingConversation);

            String notificationMsg = "已经处理了您举报的对象，感谢您的反馈！";
            LocalDateTime currentTime = LocalDateTime.now();

            Integer conversationId;
            if (existingConversation == null) {
                // 3. 如果不存在对话，创建新对话
                Conversations newConversation = new Conversations();
                newConversation.setBuyerId(32); // 系统管理员ID
                newConversation.setSellerId(stuId);
                newConversation.setLastMsg(notificationMsg);
                newConversation.setLastTime(currentTime);
                newConversation.setUnreadCount(1);
                newConversation.setStatus("pending");
                newConversation.setGoodsId(0);  // 系统消息使用0作为商品ID

                log.info("准备创建新对话: {}", newConversation);
                conversationsMapper.insert(newConversation);
                log.info("新对话创建成功，插入后的对话对象: {}", newConversation);
                
                if (newConversation.getConvId() == null) {
                    throw new RuntimeException("创建对话失败：未能获取到会话ID");
                }
                conversationId = newConversation.getConvId();
                log.info("获取到新对话ID: {}", conversationId);
            } else {
                // 4. 如果存在对话，更新对话
                existingConversation.setLastMsg(notificationMsg);
                existingConversation.setLastTime(currentTime);
                existingConversation.setUnreadCount(existingConversation.getUnreadCount() + 1);
                existingConversation.setStatus("pending");

                log.info("准备更新现有对话: {}", existingConversation);
                conversationsMapper.update(existingConversation);
                log.info("对话更新成功");
                
                conversationId = existingConversation.getConvId();
                log.info("使用现有对话ID: {}", conversationId);
            }

            // 5. 创建新消息
            Messages message = new Messages();
            message.setConversationId(conversationId);
            message.setSenderId(32); // 系统管理员ID
            message.setContent(notificationMsg);
            message.setTimestamp(currentTime);
            message.setType("text");

            log.info("准备创建新消息: {}", message);
            messagesMapper.insert(message);
            log.info("新消息创建成功，消息对象: {}", message);
            
            log.info("举报处理完成");
        } catch (Exception e) {
            log.error("处理举报过程中发生错误: ", e);
            throw e;
        }
    }

    // 驳回举报
    @Override
    public void rejectReport(Integer reportId) {
        try {
            log.info("开始驳回举报: reportId={}", reportId);
            reportMapper.updateToRejected(reportId);
            log.info("举报驳回成功");
        } catch (Exception e) {
            log.error("驳回举报过程中发生错误: ", e);
            throw e;
        }
    }
}